package com.idbk.chargestation.util;

import android.support.annotation.NonNull;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.idbk.chargestation.BuildConfig;
import com.idbk.chargestation.bean.JsonBase;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * json解析 工具类
 * @author lupc
 *
 */
public class GsonUtils {

	private final static String TAG = GsonUtils.class.getSimpleName();

	public static <T> T toBean(Class<T> type, InputStream is){
		T obj = null;	
		InputStreamReader reader = null;
		try {
			Gson gson = new GsonBuilder()
			.setDateFormat("yyyy-MM-dd HH:mm:ss")
			.create();  	
			reader = new InputStreamReader(is);				
			obj = gson.fromJson(reader, type);
		} catch (Exception e) {
			Log.e(TAG, "解析GSON错误", e);
		} finally {
			try {
				reader.close();
			} catch (Exception e2) {
				Log.e(TAG, "关闭流错误", e2);
			}				
		}			
		return obj;
	}

	public static <T> T toBean(Class<T> type, byte[] bytes){
		if (bytes == null) {
			return null;
		}
		try {
			String res = new String(bytes,"UTF-8");
			Log.d(TAG, "返回的字符：" + res);
		} catch (Exception e) {
			Log.e(TAG, "转换字节数组到字符串失败", e);
		}		
		return toBean(type, new ByteArrayInputStream(bytes));
	}

//	@NonNull
	public static <T extends JsonBase> T toBean(Class<T> type, @NonNull String json){
		T obj = null;
		if (BuildConfig.DEBUG) {
			Log.w(TAG, "json to Bean: " + json);
		}
		try {
			Gson gson = new GsonBuilder()
			.setDateFormat("yyyy-MM-dd HH:mm:ss")
			.create();  
			obj = gson.fromJson(json, type);
		} catch (Exception e) {
			Log.e(TAG, "解析GSON错误", e);
		}
		return obj;
	}
		
}
